<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.palyStatus" class="filter-item" placeholder="状态" :clearable="true">
        <el-option value="0" label="正常" />
        <el-option value="1" label="停用" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" prop="id" align="center">
        <template slot-scope="{row}">
          <span>1</span>
        </template>
      </el-table-column>
      <el-table-column label="清单名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.playName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投放位置" align="center">
        <template slot-scope="{row}">
          <span>{{ row.playName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="可用状态">
        <template slot-scope="{row}">
          <span>{{ row.playStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制作人">
        <template slot-scope="{row}">
          <span>{{ row.userType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="info" size="mini" @click="handleDetail(row,$index)">
            详情
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新增/编辑考卷 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <el-row>
          <el-col>
            <el-form-item label="标题" prop="title">
              <el-input v-model="temp.playName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="简介" prop="title">
              <el-input
                v-model="textarea"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="推送频率" prop="title">
              <el-select v-model="temp.pinlv" class="filter-item" placeholder="请选择">
                <el-option value="1" label="每天1次" />
                <el-option value="2" label="每天2次" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="title">
              <el-select v-model="temp.testPaperStatus" class="filter-item" placeholder="请选择">
                <el-option value="0" label="正常" />
                <el-option value="1" label="停用" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" /> -->
    <el-drawer :title="testpaperTitle" :visible.sync="drawerFormVisible" size="60%" direction="ltr">
      <div class="testpaper-container">
        <div class="testpaper-header">
          <el-button type="primary" @click="handleObjectCreate()">
            新增
          </el-button>
        </div>
        <div class="testpaper-body">
          <draggable group="people" @start="drag=true" @end="drag=false">
            <el-card v-for="(item,index) in testPaperList" :key="index" class="box-card" style="margin-bottom:10px">
              <div slot="header" class="clearfix">
                <span>{{ `资源${index+1}： `+item.resourceName }}</span>
                <div style="float: right;">
                  <el-button style="padding: 5px;margin-right:5px" type="primary" @click="handleSubjectUpdate(item,index)">编辑</el-button>
                  <el-button style=" padding: 5px" type="danger" @click="handleSubjectDelete(item,index)">删除</el-button>
                </div>
              </div>
              <div v-for="o in 6" :key="o">
                <!-- 遍历选项 option1-option6 -->
                <p v-show="item[`${'option'+o}`]" class="text item">{{ '选项'+o+'： '+item[`${'option'+o}`] }}</p>
              </div>
            </el-card>
          </draggable>

        </div>
        <!-- <div class="testpaper-footer" style="text-align:right">
          <el-button @click="drawerFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            保存
          </el-button>
        </div> -->
      </div>

    </el-drawer>
    <!-- 新增/编辑考题 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="innerdialogFormVisible" width="30%">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <!-- <el-row>
          <el-col>
            <el-form-item label="题干" prop="title">
              <el-input v-model="subjectTemp.content" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
          <el-row>
            <el-col>
              <el-form-item label="资源名称" prop="title">
                <el-input v-model="subjectTemp.resourceName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="资源url" prop="title">
                <el-input v-model="subjectTemp.resourceUrl" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="11">
              <el-form-item label="资源状态" prop="type">
                <el-select v-model="subjectTemp.resourceStatus" class="filter-item" placeholder="请选择">
                  <el-option value="0" label="正常" />
                  <el-option value="1" label="停用" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="资源类型" prop="type">
                <el-select v-model="subjectTemp.resourceType" class="filter-item" placeholder="请选择">
                  <el-option value="0" label="图片" />
                  <el-option value="1" label="视频" />
                  <el-option value="2" label="其他" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerdialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createSubjectData():updateSubjectData()">
          保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<style>
  .el-card__body{
    padding:0 20px;
  }
  .el-drawer__body{
   height:100%
  }
  .testpaper-container{
    display: flex;
    flex-direction: column;
    height: 100%;
    padding:0 20px 20px;
    box-sizing: border-box
  }

  .testpaper-body{
    flex: 1;
    overflow-y:scroll;
  }

.testpaper-footer,.testpaper-header{
  width: 100%;
  padding:10px;
}
</style>
<script>

import { pageQuareApi, getOptionalResource, editApi, addApi, getByIdApi, DeleteApi, getQuestionFromPaper } from '@/api/sysmanage'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import draggable from 'vuedraggable'
import { parseTime } from '@/utils'
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'Opsurvey',
  components: { draggable, Pagination },
  directives: { waves },
  data() {
    return {
      /* eslint-disable */
      value:'',
      innerdialogFormVisible:false,
      // getTypeList:[],
      OrgList:[],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
       palyStatus:''
      },
      temp:  {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      updateObj:{
        index:'',
        data:[]
      },
      dialogFormVisible:false,
      drawerFormVisible:false,
      testpaperTitle:'',
      paperId:'',
      testPaperList:[],//考题列表,
      subjectTemp:'',
      updateSubjectObj:'' 
    }
  },
  created() {
    this.handleFilter()
  },
  methods: {
    getList() {
      this.listLoading = true
      pageQuareApi(this.listQuery,'play').then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {//重置修改模态框
      this.temp = {
        "orgId": '',
        "paperTitle": "",
        "testPaperStatus": ""
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        let num=Math.random()
        if (valid=true) {
          addApi(this.temp,'testPaper').then((res) => {
            const{code,message,data}=res
            if(code==='200'){
              this.$message({
                message: message,
                type: 'success',
              })
               this.dialogFormVisible = false
               this.list.unshift(data)
            }else{
              this.$message({
                message: message,
                type: 'warning',
              })
            }
          })
        }
      })
    },
    handleDetail(row,index){
      this.testpaperTitle=row.paperTitle
      const {id}=row
      this.paperId=id
      getOptionalResource({id}).then(res=>{
        const {code,id,message,data}=res
        if(code==="200"){
            this.drawerFormVisible=true
            this.testPaperList=data?data:[]
        }else{
          this.$message({
            message: message,
            type: 'success',
          })
        }
      })

    },
    // -----------------------------------------------------
    resetObjectTemp(){
      this.subjectTemp={
        "id":this.paperId,
        "resourceName": "",
        "resourceStatus": "",
        "resourceType": "",
      }
    },
    handleObjectCreate(){
      this.resetObjectTemp()
      this.dialogStatus = 'create'
      this.innerdialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createSubjectData(){
       addApi(this.subjectTemp,'resource').then((res) => {
        const{code,message,data}=res
        console.log("TCL: createSubjectData -> data", data)
        if(code==='200'){
          this.$message({
            message: message,
            type: 'success',
          })
            this.dialogFormVisible = false
            this.testPaperList.unshift(data)
        }else{
          this.$message({
            message: message,
            type: 'warning',
          })
        }
      })
    },
    
    handleSubjectUpdate(row,index) {
        this.subjectTemp = Object.assign({},row)
        this.updateSubjectObj={
          index:index,
          data:row
        }
        //  getByIdApi({id:row.id},'resource').then(res=>{
        //   console.log("TCL: handleUpdate -> res", res)
        // }).catch()
      this.dialogStatus = 'update'
      this.innerdialogFormVisible = true
    },
    updateSubjectData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid=true) {
           const {index,data}=this.updateSubjectObj
          const tempData = Object.assign({}, this.subjectTemp)
          // tempData.id=data.id
           let query={
            "id":data.id,
            "resourceName": tempData.resourceName,
            "resourceStatus": tempData.resourceStatus,
            "resourceType": tempData.resourceType,
            "resourceUrl": tempData.resourceUrl,
          }
          editApi(query,'resource').then((res) => {
            this.innerdialogFormVisible = false
            const {data,index,message}=res
            if(res.code==='200'){
               this.$message({
                message: res.message,
                type: 'success',
              })
              const row=Object.assign(data, tempData)
              this.testPaperList.splice(index,1,row)
            }else{
               this.$message({
                message: res.message||'修改失败',
                type: 'error'
              })
            }
           
          })
        }
      })
    },
    handleSubjectDelete(row,index){
      console.log("TCL: handleSubjectDelete -> row", row)
      this.$confirm('此操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
         DeleteApi({id:row.id},'resource').then(res=>{
             this.$message({
                message: res.message,
                type: 'success'
              })
              this.testPaperList.splice(index,1)
          }).catch(err=>{
             this.$message({
                message:err.message,
                type: 'error'
              })
          })
       
        // row.status = status
      })
    },
     // -----------------------------------------------------
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid=true) {
          const {index,data}=this.updateObj
          const tempData = Object.assign({}, this.temp)
          tempData.id=data.id
          editApi(tempData,'testPaper').then((res) => {
            this.dialogFormVisible = false
            if(res.code==='200'){
               this.$message({
                message: res.message,
                type: 'success',
              })
             
              const row=Object.assign(data, this.temp)
              console.log("TCL: updateData -> row", row)
              this.list.splice(index,1,row)
            }else{
               this.$message({
                message: res.message||'修改失败',
                type: 'error'
              })
            }
           
          })
        }
      })
    },
    handleUpdate(row,index) {
      this.temp = {
        "orgId": row.orgId,
        "paperTitle": row.paperTitle,
        "testPaperStatus": row.testPaperStatus
      }
      this.updateObj={
        index:index,
        data:row
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleDelete(row,index) {
      this.$confirm('此操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
         DeleteApi({id:row.id},'play').then(res=>{
             this.$message({
                message: res.message,
                type: 'success'
              })
              this.list.splice(index,1)
          }).catch(err=>{
             this.$message({
                message:err.message,
                type: 'error'
              })
          })
       
        // row.status = status
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
   
  }
}
</script>
